﻿using LogionDemo.Common.UserEventArgs;
using System.Runtime.Caching;

namespace LogionDemo.Common.Helper
{
	public static class CacheHelper
	{
		private static readonly ObjectCache _cache = MemoryCache.Default;

		/// <summary>
		/// 过期事件
		/// </summary>
		public static event EventHandler<CacheItemExpiredEventArgs>? CacheItemExpiredEvent;

		public static void Add(object value, CacheItemPolicy policy, string key = "UserToken")
		{
			// 过期事件
			policy.RemovedCallback += CacheItemRemovedCallback;

			_cache.Set(key, value, policy);
		}

		/// <summary>
		/// 获取缓存
		/// </summary>
		/// <typeparam name="T">类型</typeparam>
		/// <param name="key">key</param>
		/// <param name="cacheItemExpired">过期回调事件</param>
		/// <returns>返回缓存</returns>
		public static T Get<T>(string key = "UserToken") => (T)_cache[key];

		public static bool Remove(string key = "UserToken") => _cache.Remove(key) != null;

		private static void CacheItemRemovedCallback(CacheEntryRemovedArguments arguments)
		{
			if (arguments.RemovedReason == CacheEntryRemovedReason.Expired)
			{
				//日志等其他逻辑
				//过期事件
				CacheItemExpiredEvent?.Invoke(null, new CacheItemExpiredEventArgs(arguments.CacheItem));
			}
			else
			{
				CacheItemExpiredEvent?.Invoke(null, null);
			}
		}
	}
}